import {Component, OnInit} from "@angular/core";
import {
  NzNotificationService,
  UploadFile,
  NzMessageService
} from "ng-zorro-antd";
import {Router} from "@angular/router";
import {HttpServcie} from "../../../service/http.service";
import {Config} from "../../../service/config";
import {ElevatorInfoBean} from "./bean/elevatorInfo.bean";
import {el} from "@angular/platform-browser/testing/src/browser_util";
import {NzModalService, NzModalSubject} from "ng-zorro-antd";
import {elevatorTypes} from "../../../service/constant/elevatorTypeConstant";
import {Observable} from "rxjs";
import {PartyBean} from "../../user/party/bean/party.bean";
import * as moment from "moment";

@Component({
  selector: "elevator-info",
  templateUrl: "./elevator-info.html",
  styleUrls: ["./elevator-info.scss"]
})
/**
 * 电梯信息列表
 */
export class ElevatorInfoPage implements OnInit {
  public flag: boolean = true;
  public data: any;
  public list: any = []; //返回的数据
  public listPro:any=[];// 项目的集合
  public modelTitle = "新增";
  public modal: any = 0;
  public elevatorlBean: ElevatorInfoBean = new ElevatorInfoBean();
  public currentModal: NzModalSubject;
  public updateData: any = {};
  public updateList: any = [];
  public total: string;
  public elevatorTypes = elevatorTypes;
  public unitFileData;
  public usedPartyName :string;
  // 定义维保单位list
  public weibaoList: any = [];
  public wuyeList :any = [];
  public config: any = Config;
  public upLoadParam: Object = {};

  //多选框
  public allChecked: any = false;
  //多选框
  public indeterminate: any = false;
  public nzSpinning: boolean = false; //遮罩
  public nzSpinning1: boolean = false;
  public isCheckedParty: any = false;
  public partyType = JSON.parse(window.localStorage["user"]).partyType;
  public partyId = JSON.parse(window.localStorage["user"]).partyId;
  public partyName = JSON.parse(window.localStorage["user"]).partyName;
  public roleId = JSON.parse(window.localStorage["user"]).roleId;
  public userName = JSON.parse(window.localStorage["user"]).userName;
  public partyLevel = JSON.parse(window.localStorage["user"]).partyLevel;
  public maintPersonList: any = [];
  public usedPersonList: any = [];
  public updateElevatorList : any = [];
  public safeUserId : string;
  public partyNameList : any = [] ;
  public branchOfficIdStr : string;
  public elevatorTypeIdStr : string; //电梯类型id
  typeList: any = [
    {
      name: '载客电梯',
      value: '1'
    }, {
      name: '液压驱动电梯',
      value: '2'
    }, {
      name: '杂物电梯',
      value: '3'
    }, {
      name: '自动扶梯',
      value: '4'
    }, {
      name: '载货电梯',
      value: '5'
    }, {
      name: '自动人行道',
      value: '6'
    }
  ]

  _startDate : any = null;
  _endDate : any = null;
  workType : string;  //要导出的记录类型
  workTypes : any = [
    {
      name : '维保记录',
      value : '1'
    },
    {
      name : '维修记录',
      value : '2'
    },
    {
      name : '巡检记录',
      value : '3'
    },
    {
      name : '救援记录',
      value : '4'
    },
    {
      name : "年度自检",
      value : '5'
    }
  ]

  //无纸化维保标识
  isPaperMantanceList = [
    {
      label: "未参与",
      value: null
    },
    {
      label: "未参与",
      value: '0'
    },
    {
      label: "已参与",
      value: '1'
    }
  ];

  //电梯投保
  public instanceName : string; //保险单位
  constructor(
    private httpServcie: HttpServcie,
    private router: Router,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService,
    private msg: NzMessageService
  ) {
    this.upLoadParam["partyId"] = this.partyId;
    this.elevatorlBean.pageSize = 10;
    this.upLoadParam["partyName"] = this.partyName;

    // 初始化时判断是否有值
    if(window.localStorage["page"] ==undefined || window.localStorage["page"]==null ){
      window.localStorage.setItem("page", "1");
      this.elevatorlBean.currentPage = 1;
    }else{
      this.elevatorlBean.currentPage = window.localStorage["page"];
    }

    if (this.partyType == "4") {
      this.isCheckedParty = true;
    }

    Observable.forkJoin(
      //查询当前用户所属机构下的物业机构
      this.httpServcie.queryByIdAndTypeList({
        // id: this.partyId,
        partyType: 2
      }),
      //查询当前用户所属机构下的维保
      this.httpServcie.queryByIdAndTypeList({
        // id: this.partyId,
        partyType: 1,
      })
    ).subscribe(data => {
      if (data[0].status == 200) {
        //物业机构
       /* this.wuyeList = data[0].data;*/
        console.log("111111111111111111111");
        console.log(this.wuyeList);
      }
      if (data[1].status == 200) {
        //维保机构
       /* this.weibaoList = data[1].data*/
      }
    });

    if (this.partyType == 1 || this.partyType == 2) {
      this.httpServcie.queryUserByPartyId(this.partyId).subscribe(data => {
        if (data.status == 200) {
          if (this.partyType == 1) {
            this.maintPersonList = data.data  ;
            this.maintPersonList.forEach((element,index) => {
              console.log(element.type == "party");
              if(element.type == "party"){
                this.maintPersonList.splice(index,1);
              }
            });
          }
          if (this.partyType == 2) {
            this.usedPersonList = data.data;
            this.usedPersonList.forEach((element,index) => {
              if(element.type == "party"){
                this.usedPersonList.splice(index,1);
              }
            });
          }
        }
      })
    }
    this.queryAll();
  }
  //查詢電梯列表
  queryAll(){
    this.nzSpinning = true;
    this.elevatorlBean.partyId =this.partyId;
    this.elevatorlBean.partyType=this.partyType;
    this.elevatorlBean.partyLevel=this.partyLevel;
    this.httpServcie.queryElevatorList(this.elevatorlBean).subscribe(
      data => {
        if (data.status == 200) {
          this.nzSpinning = false;
          this.list = data.data.list;
          this.weibaoList = data.data.weibaoList;
          this.listPro = data.data.listPro;
          this.wuyeList = data.data.wuyeList;
          this.total = data.data.total;
          console.log(data.data.list);
        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          // 异常
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      })
  }
  ngOnInit() {

  }




  delete() {
    const deleteList: any = [];
    const thiss: any = this;
    this.list.forEach(element => {
      if (element.checked) {
        deleteList.push(element.id + "");
      }
    });

    if (deleteList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }

    this.modalService.confirm({
      title: "您是否确认要删除这 " + deleteList.length + " 条内容",
      content: "<b>一旦删除，无法还原</b>",
      onOk() {
        let ob = thiss.httpServcie.deleteElevator({ids: deleteList}); //批量删除
        ob.subscribe(
          data => {
            if (data.status == 200) {
              thiss._notification.create("success", "成功", "删除成功！");
              //thiss.userBean.currentPage = 1;
              thiss.query();
            } else {
              thiss._notification.create("error", "错误提示", data.message);
            }
          },
          error => {
            thiss._notification.create("error", "错误提示", "删除失败！");
          }
        );
      },
      onCancel() {
      }
    });
  }
  /**
   * 批量删除
   */
  batchDelete() {
    const deleteList: any = [];
    const thiss: any = this;
    this.list.forEach(element => {
      if (element.checked) {
        deleteList.push(element.id + "");
      }
    });

    if (deleteList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }

    this.modalService.confirm({
      title: "您是否确认要删除这 " + deleteList.length + " 条内容",
      content: "<b>一旦删除，无法还原</b>",
      onOk() {
        let ob = thiss.httpServcie.batchDeleteElevator({ids: deleteList}); //批量删除
        ob.subscribe(
          data => {
            if (data.status == 200) {
              thiss._notification.create("success", "成功", "删除成功！");
              //thiss.userBean.currentPage = 1;
              thiss.queryAll();
            } else {
              thiss._notification.create("error", "错误提示", data.message);
            }
          },
          error => {
            thiss._notification.create("error", "错误提示", "删除失败！");
          }
        );
      },
      onCancel() {
      }
    });
  }



  batchExport() {
    if(this.workType == null || this.workType == ''){
      this._notification.create("warning", "警告提示", "导出前，请先选择要导出的记录类型！");
      return;
    }
    if(this.workType == '3' && (this._startDate == null || this._startDate == '')){
      this._notification.create("warning", "警告提示", "导出巡检记录，请先指定导出月份！");
      return;
    }
    let elevatorList = [];  //勾选的电梯信息
    this.list.forEach(element => {
      if(element.checked){
        elevatorList.push(element);
      }
    });
    if(elevatorList.length == 0){
      this._notification.create("warning", "警告提示", "请勾选要导出记录的电梯！");
      return;
    }

    let tempStartDate = "";
    let tempEndDate = "";
    if(this._startDate != null){
      tempStartDate = moment(this._startDate).format("YYYYMMDDHHmmss");
    }
    if(this._endDate != null){
      tempEndDate = moment(this._endDate).format("YYYYMMDDHHmmss");
    }
    let param = {
      workType : this.workType,
      elevatorList : elevatorList,
      startDate : tempStartDate,
      endDate : tempEndDate,
    }
    /**
     * 巡检的参数不一样
     */
    if(this.workType == '3'){
      let mon = (this._startDate.getMonth() + 1) + "";
      if (((this._startDate.getMonth() + 1) + "").length == 1) {
        mon = "0" + (this._startDate.getMonth() + 1);
      }
      let nowmont = this._startDate.getFullYear() + "" + mon;
      param.startDate = nowmont;
    }

    this.httpServcie.batchExportWorkRecords(param).subscribe(data =>{
      if (data.status == 200) {
        if(data.data.fileUrl == null || typeof (data.data.fileUrl) == undefined){
          console.log("haha"+data.data.fileUrl);
          this._notification.create('error', '提示', "无可导出的作业记录");
          return;
        }
        this.download(data.data.fileUrl, data.data.fileName);
        this._notification.create('success', '提示', "导出成功");
      } else {

      }
    })
  }



  //跳转详细页面
  toDetail(data) {
    this.router.navigate(["/home/elevator-detail", {elevatorId : data.id}]);
  }

  //弹出编辑模态框页面
  toEdit(data) {
    this.router.navigate(["/home/elevator-unit-file", data]);
  }

  //table加载数据时
  displayDataChange($event) {
    this.list = $event;
    this.refreshStatus();
  }

  //添加
  add(titleTpl, contentTpl, footerTpl) {
    this.modelTitle = "添加";
    this.modal = 0;

    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 900,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  update(titleTpl, contentTpl, footerTpl) {
    this.modelTitle = "修改";
    this.modal = 1;
    const updateList: any = [];

    this.list.forEach(element => {
      if (element.checked) {
        updateList.push(element);
        this.updateData = element;
      }
    });
    if (updateList.length > 1) {
      // 异常
      this._notification.create("warning", "警告提示", "只能选中一条数据！");
      return;
    }
    if (updateList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }

    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 900,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  /**
   * 给电梯投保
   * @param titleInstance
   * @param contentInstance
   * @param footerInstance
   */
  goInstance(titleInstance,contentInstance,footerInstance){
    this.modelTitle = "电梯投保";
    this.modal = 6;
    const updateList: any = [];
    let isInsure = false;
    this.list.forEach(element => {
      if (element.checked) {
        updateList.push(element);
        this.updateData = element;
        if(element.isInsure == '是'){
          isInsure = true;
        }
      }
    });
    if (updateList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }
    if(isInsure){
      this._notification.create("warning", "警告提示", "请选择未参与投保的电梯！");
      return;
    }

    this.currentModal = this.modalService.open({
      title: titleInstance,
      content: contentInstance,
      footer: footerInstance,
      maskClosable: false,
      width: 900,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  /**
   * 提交保险申请
   */
  submitInstance(){

  }

  //批量修改
  batchUpdate(titleTpl, contentTpl, footerTpl) {
    // 批量修改前清空 updateList
    this.updateList = [];
    this.modelTitle = "批量修改";
    this.modal = 3;
    // 判断是否选择的记录数据
    this.list.forEach(element => {
      if (element.checked) {
        this.updateList.push(element);
      }
    });
    if (this.updateList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请至少选中一条数据！");
      return;
    }
    for (let i = 0; i <this.updateList.length-1 ; i++) {
      if(this.updateList[i].maintenancePartyId != this.updateList[i+1].maintenancePartyId){
        this._notification.create("warning", "警告提示", "请选择相同的维保单位！");

        return false;
      }
    }

    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 900,
      style: {
        top: "20px"
      },

      onOk() {
        console.log("Click ok");
      }
    });
  }
  // 修改完之后进行界面刷新
  addOutPut(event) {
    setTimeout(() => {
      /* destroy方法可以传入onOk或者onCancel。默认是onCancel */
      this.currentModal.destroy();
      this.currentModal = null;
    }, 200);
    // this.elevatorlBean.currentPage = 1;
    this.queryAll()
  }



  /**
   * 批量修改电梯管理员
   */
  batchUpdateSafeUser(titleTpl, contentTpl, footerTpl) {
    // 批量修改前清空 updateList
    this.modelTitle = "批量修改安全管理员";
    // 判断是否选择的记录数据
    this.updateElevatorList = [];
    this.list.forEach(element => {
      if (element.checked) {
        this.updateElevatorList.push(element);
      }
    });
    if (this.updateElevatorList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请至少选中一条数据！");
      return;
    }

    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 900,
      style: {
        top: "20px"
      },

      onOk() {
        console.log("Click ok");
      }
    });
  }
  /**
    批量修改所属分局
  * */
  batchUpdateChessboard(titleTpl, contentTpl, footerTpl) {
    // 批量修改前清空 updateList
    this.modelTitle = "批量修改所属分局";
    // 判断是否选择的记录数据
    this.updateElevatorList = [];
    this.list.forEach(element => {
      if (element.checked) {
        this.updateElevatorList.push(element);
      }
    });
    if (this.updateElevatorList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请至少选中一条数据！");
      return;

    }


    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 900,
      style: {
        top: "20px"
      },

      onOk() {
        console.log("Click ok");
      }
    });
    this.queryChessboard();
  }

  /**
   * 批量修改电梯类型
   * @param titleTpl
   * @param contentTpl
   * @param footerTpl
   */
  batchUpdateElevatorType(titleTpl, contentTpl, footerTpl) {
    // 批量修改前清空 updateList
    this.modelTitle = "批量修改电梯类型";
    // 判断是否选择的记录数据
    this.updateElevatorList = [];
    this.list.forEach(element => {
      if (element.checked) {
        this.updateElevatorList.push(element);
      }
    });
    if (this.updateElevatorList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请至少选中一条数据！");
      return;

    }


    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 900,
      style: {
        top: "20px"
      },

      onOk() {
        console.log("Click ok");
      }
    });
    this.queryChessboard();
  }

  queryChessboard() {
    this.httpServcie.chessboardGetList(null).subscribe(
      data =>{
        if(data.status ==200){
          this.partyNameList = data.data.list;
        }else {
          // 异常
          this._notification.create("error", "错误提示", data.message);
        }
      }
    )

  }
  updateSafeUser(){
    let param = {
      safeUserId : this.safeUserId,
      elevatorNums : null
    }
    let list = [];
    this.updateElevatorList.forEach(element => {
      list.push(element.elevatorNum);
    });
    param.elevatorNums = list;
    this.httpServcie.elevatorSafeUserUpdate(param).subscribe(data => {
      if (data.status != "200") {
        this._notification.create("error", "错误提示", "修改失败！");
      }
      if (data.status == 200) {
        this._notification.create("success", "", "修改成功！");
        this.quit();
      }
    });

  }

  updateChessboard(){
    let param = {
      branchOfficeId : this.branchOfficIdStr,
      elevatorNums : null
    }
    let list = [];
    this.updateElevatorList.forEach(element => {
      list.push(element.elevatorNum);
    });
    param.elevatorNums = list;
    this.httpServcie.chessboardUpdate(param).subscribe(data => {
      if (data.status != "200") {
        this._notification.create("error", "错误提示", "修改失败！");
      }
      if (data.status == 200) {
        this._notification.create("success", "", "修改成功！");
        this.quit();
      }
    });

  }
  /*修改电梯类型*/
  updateElevatorType(){
    let param = {
      elevatorTypeId : this.elevatorTypeIdStr,
      elevatorNums : null
    }
    let list = [];
    this.updateElevatorList.forEach(element => {
      list.push(element.elevatorNum);
    });
    param.elevatorNums = list;
    this.httpServcie.updateElevatorType(param).subscribe(data => {
      if (data.status != "200") {
        this._notification.create("error", "错误提示", "修改失败！");
      }
      if (data.status == 200) {
        this._notification.create("success", "", "修改成功！");
        this.quit();
      }
    });
  }

  quit(){
    this.currentModal.destroy();
    this.queryAll();
  }
  //重置选择框
  refreshStatus() {
    const allChecked = this.list.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.list.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }

  //全选
  checkAll(value) {
    if (value) {
      this.list.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.list.forEach(data => (data.checked = false));
    }
  }

  //分页
  nzPageSizeChange(event) {
    this.elevatorlBean.pageSize = event;
    this.elevatorlBean.currentPage = 1;
    this.queryAll();
  }

  //输入框的方法
  nzPageIndexChange(event) {
    this.elevatorlBean.currentPage = event;
    this.queryAll();
  }

  //当前页
  nzPageIndexClickChange(event) {
    this.elevatorlBean.currentPage = event;
    window.localStorage.setItem("page",JSON.stringify(this.elevatorlBean.currentPage));
    this.queryAll();
  }

  // 单位信息档案编辑回调
  callBack(event) {
    this.currentModal.destroy();
  }

  // 单位信息档案编辑取消回调
  cancel(event) {
    this.currentModal.destroy();
  }

  //上传

  showUpload(titleUpload, contentUpload, footerUpload) {
    this.currentModal = this.modalService.open({
      title: titleUpload,
      content: contentUpload,
      footer: footerUpload,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },

      onOk() {
        console.log("Click ok");
      }
    });
  }

  //上传回调
  uploadChage(info: { file: UploadFile }) {
    console.log(info);
    if (info.file.status === "uploading") {
      return;
    }
    this.nzSpinning1 = false;
    if (info.file.status === "done") {
      //设置为接口的查询不然反显有时候没用
      if (info.file.response.status != "200") {
        this._notification.create(
          "error",
          "错误提示",
          info.file.response.message
        );
      } else {
        if (info.file.response.data.data != null && info.file.response.data.data != '' && info.file.response.data.data != undefined) {
          var message = info.file.response.data.data;

          this.modalService.confirm({
            title: "成功反馈",
            content: message,
            onOk() {
            },
            onCancel() {
            }
          });
        }
        this._notification.create("success", "提示", "导入成功");
        this.currentModal.destroy();
        this.queryAll();
      }
    }
  }
  /**
   * 批量修改维保/使用 之后的回调函数刷新维保方法界面
   * @param info
   */
  //上传回调
  uploadChageMenu(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    this.nzSpinning1 = false;
    if (info.file.status === "done") {
      //设置为接口的查询不然反显有时候没用
      if (info.file.response.status != "200") {
        this._notification.create(
          "error",
          "错误提示",
          info.file.response.message
        );
      } else {
        this._notification.create("success", "提示", "导入成功");
        this.currentModal.destroy();
        this.queryAll();
      }
    }
  }
  beforeUpload = (file: File) => {
    this.nzSpinning1 = true;
    return true;
  };

  download(url, name) {
    let link = document.createElement("a");
    let body = document.querySelector("body");

    this.getBlob(this.config.IP + this.config.API.getUpload + url).then(
      blob => {
        link.href = window.URL.createObjectURL(blob);
        link.download = name;
        // fix Firefox
        link.style.display = "none";
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      }
    );
  }

  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }

  importEle(importUpload, contentImportUpload, footerImportUpload) {
    this.currentModal = this.modalService.open({
      title: importUpload,
      content: contentImportUpload,
      footer: footerImportUpload,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }
  importEleType(importUploadEleType, contentImportUploadEleType, footerImportUploadEleType) {
    this.currentModal = this.modalService.open({
      title: importUploadEleType,
      content: contentImportUploadEleType,
      footer: footerImportUploadEleType,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

}
